package com.ruoyi.business.youdaoController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("ownYDThirdApi")
public class YouDaoThirdController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IDynamicSearchService dynamicSearchService;

    private final static String CLASSESEN = "youdao";





    @Log(title = "有道", businessType = BusinessType.RTA, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);
        //imei\idfa\sid 如果都为111111111111 则返回body为1
        String imei = getMapValue(baseParamsMap, "imei");
        String idfa = getMapValue(baseParamsMap, "idfa");
        String sid = getMapValue(baseParamsMap, "sid");
        if("111111111111".equals(imei) && "111111111111".equals(idfa) && "111111111111".equals(sid)){
            return 1;
        }
        if("222222222222".equals(imei) && "222222222222".equals(idfa) && "222222222222".equals(sid)){
            return 0;
        }


        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }

        String url = channelDetail.get("rta_adress") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);



        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            ip = null;
        }
        baseParamsMap.put("reqId", dmpid);
        if(StringUtils.isNotBlank(idfa)){
            baseParamsMap.put("idfa", idfa.toUpperCase());
        }
        if(StringUtils.isNotBlank(imei)){
            //imei转大写
            imei = imei.toUpperCase();
            //imei进行Md5
            imei = DigestUtils.md5DigestAsHex(imei.getBytes());
            baseParamsMap.put("imeiMd5", imei.toUpperCase());
        }



        List<String> tempList = new ArrayList<>();
        for(String key: baseParamsMap.keySet()){
            tempList.add(key+"="+baseParamsMap.get(key));
        }
        String requestParameters = String.join("&", tempList);
        String reportResultsStr = "";
        if("POST".equals(requestType)){
            reportResultsStr = HttpUtils.sendPost(requestAddress, requestParameters, ip, ua);
        }else{
            reportResultsStr = HttpUtils.sendGet(requestAddress, requestParameters, ip, ua);
        }

        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
//            return reportResults==null?"":reportResults;
            if(reportResults.getInteger("code") == 0){
                return reportResults.getJSONObject("data").getInteger("bidStatus");
            }
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
//        return reportResultsStr;
        return 0;
    }




    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }





}
